package com.qf.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author 王博康
 * @version 1.0
 * @project 01_maven_mybatis
 * @description: TODO
 * @date 2022/3/2 15:02 星期三
 */
public class MyBatilUtil {
    private static ThreadLocal<SqlSession> sqlSessionThreadLocal=new ThreadLocal<>();
    private static SqlSessionFactory sessionFactory;
    private static SqlSession getSqlSession() throws IOException {
        if (sessionFactory==null){
            InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
            sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }
        SqlSession sqlSession = sessionFactory.openSession();
        sqlSessionThreadLocal.set(sqlSession);
        return sqlSession;
    }
    public static <T> T getMapper(Class<T> mapperclass) throws IOException {
        SqlSession sqlSession = sqlSessionThreadLocal.get();
        if (sqlSession==null){
            sqlSession=getSqlSession();
        }
        T mapper = sqlSession.getMapper(mapperclass);
        return mapper;
    }
    public static void commit(){
        SqlSession sqlSession = sqlSessionThreadLocal.get();
        if (sqlSession!=null){
            sqlSession.commit();
        }
    }
    public static void rollback(){
        SqlSession sqlSession = sqlSessionThreadLocal.get();
        if (sqlSession!=null){
            sqlSession.rollback();
        }
    }
    public static void close(){
        SqlSession sqlSession = sqlSessionThreadLocal.get();
        if (sqlSession!=null){
            sqlSession.close();
            sqlSessionThreadLocal.remove();
        }
    }
}
